/**
 * @description 对象深拷贝
 * @param {*} obj 要拷贝的对象
 * @param {*} hash 缓存对象 (可不传)
 * @return {*} 拷贝后的对象
 */
interface DeepCopy {
	(obj: any, hash?: WeakMap<any, any>): any;
}

const deepCopy: DeepCopy = function (obj, hash = new WeakMap()) {
	// 针对基本类型直接返回
	if (obj == null) return obj;
	if (obj instanceof Date) return new Date(obj);
	if (obj instanceof RegExp) return new RegExp(obj);

	if (hash.has(obj)) return hash.get(obj);

	let cloneObj: any;
	if (Array.isArray(obj)) {
		cloneObj = [];
	} else if (typeof obj === 'object') {
		cloneObj = {};
	} else {
		return obj;
	}

	hash.set(obj, cloneObj);

	for (let key in obj) {
		// 使用Object.prototype.hasOwnProperty.call来避免潜在的原型链问题
		if (Object.prototype.hasOwnProperty.call(obj, key)) {
			cloneObj[key] = deepCopy(obj[key], hash);
		}
	}

	return cloneObj;
};
export default deepCopy;
